package org.example.btchat.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.example.btchat.Message;
import android.bluetooth.BluetoothSocket;

public class Connection
{
	public OutputStream output = null;
	public InputStream input = null;
	public BluetoothSocket socket = null;
	private ServerService server;
	
	@SuppressWarnings("unused")
	private Thread thread;
	
	public Connection(ServerService server, BluetoothSocket socket) throws IOException
	{
		try
		{
			this.socket = socket;
			this.input = socket.getInputStream();
			this.output = socket.getOutputStream();
		}
		catch(IOException e)
		{
			this.close();
			throw e;
		}
		
		this.server = server;
		
		this.thread = new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				try
				{
					read();
				}
				catch(IOException e)
				{
					Connection.this.close();
				}
			}
		});
	}
	
	protected void read() throws IOException
	{
		int pos;
		byte[] read = new byte[1];
		String buffer = "";
		
		while(true)
		{
			read[0] = (byte) input.read();
			buffer += read;
			
			pos = buffer.indexOf("\0\0");
			if(pos != -1)
			{
				parse(buffer.substring(0, pos));
				buffer = buffer.substring(pos + 2);
			}
		}
	}
	
	private void parse(String buffer)
	{
		int pos = buffer.indexOf("\0");
		if(pos == -1)
			return;
		
		String source = buffer.substring(0, pos);
		String message = buffer.substring(pos + 1);
		
		server.onMessageSent(new Message(source, message));
	}
	
	public void close()
	{
		try
		{
			this.input.close();
		}
		catch(Exception e)
		{}
		
		try
		{
			this.output.close();
		}
		catch(Exception e)
		{}
		
		try
		{
			this.socket.close();
		}
		catch(Exception e)
		{}
	}
	
	public synchronized void send(Message msg) throws IOException
	{
		output.write(msg.getSource().getBytes());
		output.write("\0".getBytes());
		output.write(msg.getMessage().getBytes());
		output.write("\0\0".getBytes());
	}
}
